﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Param = ClassLibrary.Parameters.Values;
using ClassLibrary;
using System.IO;
using System.Resources;

namespace ControlLibrary
{
    [ComVisible(true)]
    public partial class Panel_Marker : UserControl
    {
        public delegate void OnSaveClick();
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnSaveClick onSaveClick;

        public delegate void OnCancelClick();
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnCancelClick onCancelClick;

        public delegate void OnModifiedClick();
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnModifiedClick onModifiedClick;

        public delegate void OnConfigCategoriesClick();
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnConfigCategoriesClick onConfigCategoriesClick;

        private bool _init;
        private bool _showRepere = false;
        private Marker _marker;
        private string _defaultTitle;

        public Marker Marker
        {
            get { return _marker; }
        }

        #region CONSTRUCTOR

        public Panel_Marker()
        {
            _init = true;
            InitializeComponent();

            panel_Empty.BringToFront();
            _init = false;
        }

        #endregion

        public void UpdateUI()
        {
            ResourceManager _RM = new ResourceManager("ControlLibrary.Panel_Marker", typeof(Panel_Marker).Assembly);
            try
            {
                toolStripButton_CancelEvent.Text = _RM.GetString("toolStripButton_CancelEvent.Text");
                toolStripButton_Generate.Text = _RM.GetString("toolStripButton_Generate.Text");
                toolStripButton_SaveEvent.Text = _RM.GetString("toolStripButton_SaveEvent.Text");
                toolStripButton_SaveMarker.Text = _RM.GetString("toolStripButton_SaveMarker.Text");
                toolStripButton_PanelGenerate.Text = _RM.GetString("toolStripButton_PanelGenerate.Text");
                toolStripButton_CancelMarker.Text = _RM.GetString("toolStripButton_CancelMarker.Text");
                cueTextBox_Title.CueText = _RM.GetString("cueTextBox_Title.CueText");
                _defaultTitle = _RM.GetString("cueTextBox_Title.CueText");

                categoryList1.UpdateUI();
                eventList.UpdateUI();
                panel_GenerateThumb1.UpdateUI();
                /*panel_DisplayMarker.UpdateUI();
                panel_EventEdition1.UpdateUI();
                panel_GenerateThumb1.UpdateUI();*/
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_Marker", "UpdateUI", e, Param.RM.GetString("MB_Error_UpdateUI"));
            }
        }

        public void ShowHidePanelMarker(bool show)
        {
            tableLayoutPanel1.Visible = show;
            tableLayoutPanel2.Visible = show;
            toolStripButton_CancelMarker.Enabled = show;
            toolStripButton_PanelGenerate.Enabled = show;
            toolStripButton_CancelMarker.Enabled = show;
            toolStripButton_SaveMarker.Enabled = show;
        }

        public bool Init()
        {
            _init = true;
            try
            {
                _marker = new Marker();
                _showRepere = false;

                tableLayoutPanel1.Visible = false;
                tableLayoutPanel2.Visible = false;
                toolStripButton_CancelMarker.Enabled = false;
                toolStripButton_PanelGenerate.Enabled = false;

                toolStripButton_SaveMarker.Enabled = false;

                panel_Empty.BringToFront();

                if (null != webBrowser1.Document)
                    webBrowser1.Document.InvokeScript("hideMarker");

                _init = false;
                return true;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_Marker", "Init", e);
                _init = false;
                return false;
            }

        }

        public bool Init(Marker marker)
        {
            bool RC = true;
            _init = true;

            try
            {
                toolStripButton_SaveMarker.Image = Properties.Resources.Save_16x16;
                _marker = marker;
                _showRepere = true;
                eventList.clear();
                ShowHidePanelMarker(true);

                if (Parameters.Values.RM.GetString("Marker_DefaultName") != _marker.title)
                    cueTextBox_Title.Text = _marker.title;
                else cueTextBox_Title.Text = string.Empty;

                foreach (Event e in _marker.events)
                    eventList.addItem(e.ID, e.dateString, e.title, e.isLink);

                categoryList1.CheckedItems = _marker.categories;
                panel_Empty.BringToFront();

                toolStripButton_CancelEvent.Visible = false;
                toolStripButton_SaveEvent.Visible = false;
                toolStripButton_Generate.Visible = false;

                //Pictures
                string img = string.Empty;
                if(null != Path.GetFileName(_marker.Img_Small))
                    img = Path.Combine(Param.localPath_Small, Path.GetFileName(_marker.Img_Small));

                if (File.Exists(img))
                    RC = pictureBoxLoadImage(pictureBox_Small,img);
                else
                {
                    //Try to download it
                    /*if (null != _marker.serverPath_Img_Small)
                    {
                        marker.localPath_Img_Small = Path.Combine(Parametres.Values.myDocSmallFolder, Path.GetFileName(_marqueur.serverPath_Img_Small));
                        bool RC = FTPUtility.DownLoadImg(_marqueur.serverPath_Img_Small, marker.localPath_Img_Small);
                        if (true == RC && File.Exists(_marqueur.localPath_Img_Small))
                            pictureBoxLoadImage(pictureBox_Icone, _marqueur.localPath_Img_Small);
                        else
                            pictureBox_Icone.Image = null;
                    }
                    else pictureBox_Icone.Image = null;*/
                    pictureBox_Small.Image = null;
                }

                if (true == RC)
                {
                    img = string.Empty;
                    if (null != Path.GetFileName(_marker.Img_Medium))
                        img = Path.Combine(Param.localPath_Medium, Path.GetFileName(_marker.Img_Medium));

                    if (File.Exists(img))
                        RC = pictureBoxLoadImage(pictureBox_Medium, img);
                    //pictureBox_Miniature.Image = new Bitmap(_marqueur.localPathInfoBulle);
                    else
                    {
                        //Try to download it
                        /*if (null != marker.serverPath_Img_Medium)
                        {
                            marker.localPath_Img_Medium = Path.Combine(Parametres.Values.myDocMediumFolder, Path.GetFileName(_marqueur.serverPath_Img_Medium));
                            bool RC = FTPUtility.DownLoadImg(_marqueur.serverPath_Img_Medium, marker.localPath_Img_Medium);
                            if (true == RC && File.Exists(_marqueur.localPath_Img_Medium))
                                pictureBoxLoadImage(pictureBox_Miniature, _marqueur.localPath_Img_Medium);
                            else
                                pictureBox_Miniature.Image = null;
                        }
                        else pictureBox_Miniature.Image = null;*/
                        pictureBox_Medium.Image = null;
                    }
                }

                //PictureBox Border Style
                if (null != pictureBox_Small.Image)
                    pictureBox_Small.BorderStyle = System.Windows.Forms.BorderStyle.None;
                else pictureBox_Small.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

                if (null != pictureBox_Medium.Image)
                    pictureBox_Medium.BorderStyle = System.Windows.Forms.BorderStyle.None;
                else pictureBox_Medium.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

                //Marker location
                if (null != webBrowser1.Document)
                {
                    object[] args = { marker.lat, marker.lng };
                    webBrowser1.Document.InvokeScript("placeMarker", args);
                }
                _init = false;
                return true;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_Marker", "Init", e);
                _init = false;
                return false;
            }
        }

        public void SetListCategorie(List<string> categories)
        {

            if (categories.Count > 0)
            {
                categoryList1.Items = categories;

                //Dans le cas ou la liste des catégorie a été modifiée en cours
                //de session (via le menu configuration -> catégories)
                //Il faut mettre à jour la liste des catégories ET checker les items
                if (null != _marker && null != _marker.categories)
                    categoryList1.CheckedItems = _marker.categories;
            }
        }

        #region EVENTLIST Events

        //NEW
        private void eventList_onNewEvent()
        {
            panel_EventEdition1.BringToFront();
            panel_EventEdition1.init(Guid.NewGuid());
            toolStripButton_Generate.Visible = false;
            toolStripButton_SaveEvent.Visible = true;
            toolStripButton_CancelEvent.Visible = true;
            toolStripButton_SaveEvent.Image = Properties.Resources.Save_16x16;
        }

        //EDIT
        private void eventList_onEditEvent(Guid guid)
        {
            panel_EventEdition1.BringToFront();

            Event e = _marker.getEventByID(guid);
            if (null != e)
            {
                panel_EventEdition1.Visible = true;
                toolStripButton_SaveEvent.Image = Properties.Resources.Save_16x16;
                panel_EventEdition1.init(e.title, e.link, e.dateBegin, e.dateEnd, e.isPeriod, e.ID);
            }
            toolStripButton_Generate.Visible = false;
            toolStripButton_SaveEvent.Visible = true;
            toolStripButton_CancelEvent.Visible = true;
        }

        //DELETE
        private void eventList_onDeleteEvent(Guid guid)
        {
            eventList_onNewEvent();
            panel_Empty.BringToFront();
            toolStripButton_CancelEvent.Visible = false;
            toolStripButton_SaveEvent.Visible = false;
            toolStripButton_Generate.Visible = false;

            _marker.removeEventByID(guid);

            toolStripButton_SaveMarker.Image = Properties.Resources.SaveNotif_16x16;
        }

        #endregion

        #region THUMBS GENERATION Events

        private bool pictureBoxLoadImage(PictureBox pb, string path)
        {
            try
            {
                //Chargement de l'image en mémoire
                FileStream fs = File.OpenRead(path);
                byte[] b = new byte[fs.Length];
                fs.Read(b, 0, b.Length);
                fs.Close();

                var ms = new MemoryStream(b);
                pb.Image = Image.FromStream(ms);
                return true;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_Marker", "pictureBoxLoadImage", e);
                return false;
            }
        }

        private void panel_GenerateThumb1_onPathDefined()
        {
            toolStripButton_Generate.Enabled = true;
        }

        #endregion

        #region PANEL_EVENTEDITION Events

        //EVENT MODIFIED
        private void panel_EventEdition1_onModified()
        {
            toolStripButton_SaveEvent.Image = Properties.Resources.SaveNotif_16x16;
            eventList.Enabled = false;
            toolStrip1.Enabled = false;


            if (null != onModifiedClick)
                onModifiedClick();
        }

        //EVENT SAVED
        private void panel_EventEdition1_onSaved(Guid ID, string titre, string lien, DateTime d1, DateTime d2, bool periode, bool newEvent)
        {
            try
            {
                Uri tmp;
                bool isLink = Uri.TryCreate(lien, UriKind.Absolute, out tmp);
                if (newEvent)
                {
                    Event e = new Event();
                    e.set(ID, titre, lien, d1, d2);
                    _marker.events.Add(e);
                    eventList.addItem(e.ID, e.dateString, e.title, e.isLink);
                }
                else
                {
                    Event e = _marker.getEventByID(ID);
                    if (null != e)
                    {
                        e.set(ID, titre, lien, d1, d2);
                        eventList.updateItem(ID, e.dateString, e.title, e.isLink);
                    }
                    else throw new Exception("_marker.getEventByID failed"); 
                }

                eventList.Enabled = true;
                toolStrip1.Enabled = true;
                panel_Empty.BringToFront();
                toolStripButton_SaveEvent.Visible = false;
                toolStripButton_CancelEvent.Visible = false;


                toolStripButton_SaveEvent.Image = Properties.Resources.Save_16x16;

                modified();
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_Marker", "panel_EventEdition1_onSaved", e, "Save Event failed");
            }
        }

        //SAVE
        private void toolStripButton_SaveEvent_Click(object sender, EventArgs e)
        {
            panel_EventEdition1.trySave();
        }

        //CANCEL
        private void toolStripButton_CancelEvent_Click(object sender, EventArgs e)
        {
            panel_EventEdition1.reset();
            eventList.Enabled = true;
            toolStrip1.Enabled = true;
            toolStripButton_SaveEvent.Image = Properties.Resources.Save_16x16;
        }

        #endregion

        #region EDIT CATEGORIES Events

        private void categoryList1_onCheckChanged()
        {
            if (!_init)
            {
                _marker.categories = categoryList1.CheckedItems;
                modified();
            }
        }

        private void categoryList1_onConfigClick()
        {
            if (null != onConfigCategoriesClick)
                onConfigCategoriesClick();
        }

        #endregion

        #region PICTUREBOX Events

        private void pictureBox_Small_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Param.localPath_Small;
            openFileDialog1.FileName = string.Empty;
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                panel_GenerateThumb1_onGenerateSmall(true, openFileDialog1.FileName, _marker.SmallWidth, _marker.SmallHeight);

        }

        private void pictureBox_Medium_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Param.localPath_Medium;
            openFileDialog1.FileName = string.Empty;
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
               panel_GenerateThumb1_onGenerateMedium(true, openFileDialog1.FileName,  _marker.MediumWidth, _marker.MediumHeight);
        }

        //SHOW panel
        private void toolStripButton_PanelGenerate_Click(object sender, EventArgs e)
        {            
            panel_GenerateThumb1.Init(_marker.MediumWidth, _marker.MediumHeight, Marker.SmallWidth, Marker.SmallHeight);
            panel_GenerateThumb1.BringToFront();

            toolStripButton_Generate.Visible = true;
            toolStripButton_SaveEvent.Visible = false;
            toolStripButton_CancelEvent.Visible = false;
        }

        //EXECUTE
        private void toolStripButton_Generate_Click(object sender, EventArgs e)
        {
            panel_GenerateThumb1.Convert();
        }

        private void panel_GenerateThumb1_onGenerateMedium(bool succeed, string imgPath, decimal width, decimal height)
        {
            if (succeed)
            {
                pictureBoxLoadImage(pictureBox_Medium, imgPath);
                _marker.Img_Medium = imgPath.Replace(Param.localPath_Root+"\\","");
                _marker.Img_Medium = _marker.Img_Medium.Replace("\\", "//");
                _marker.Img_Medium = _marker.Img_Medium.Insert(0, "..//");
                _marker.MediumWidth = width;
                _marker.MediumHeight = height;
                modified();
            }
            else
            {
                pictureBox_Medium.Image = null;
                _marker.Img_Medium = string.Empty;
            }

            if (null != pictureBox_Medium.Image)
                pictureBox_Medium.BorderStyle = System.Windows.Forms.BorderStyle.None;
            else pictureBox_Medium.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        }

        private void panel_GenerateThumb1_onGenerateSmall(bool succeed, string imgPath, decimal width, decimal height)
        {
            try
            {
                if (succeed)
                {
                    pictureBoxLoadImage(pictureBox_Small, imgPath);
                    _marker.Img_Small = imgPath.Replace(Param.localPath_Root+"\\", "");
                    _marker.Img_Small = _marker.Img_Small.Replace("\\", "//");
                    _marker.Img_Small = _marker.Img_Small.Insert(0, "..//");
                    _marker.SmallHeight = height;
                    _marker.SmallWidth = width;
                    modified();
                }
                else
                {
                    pictureBox_Small.Image = null;
                    _marker.Img_Small = string.Empty;
                }

                if (null != pictureBox_Small.Image)
                    pictureBox_Small.BorderStyle = System.Windows.Forms.BorderStyle.None;
                else pictureBox_Small.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panl_Marker", "panel_GenerateThumb1_onGenerateSmall", e);
            }
        }


        #endregion

        #region WEBBROWSER

        public bool setGMap()
        {
            try
            {
                webBrowser1.Navigate(Path.Combine(Application.StartupPath, Param.localPath_EmptyMap));
                return true;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_Marker", "setGmap", e);
                return false;
            }
        }

        private void EditMarker_Load(object sender, EventArgs e)
        {
            try
            {
                webBrowser1.ObjectForScripting = this;

            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("Panel_Marker", "EditMarker_Load", ex);
            }
        }

        public float LatFromCS()
        {
            if (null != _marker)
                return (float)_marker.lat;
            else return 0;

        }
        public float LngFromCS()
        {
            if (null != _marker)
                return (float)_marker.lng;
            else return 0;
        }

        public void FromGM_MarkerDropEnd(float Lat, float Lon)
        {
            _marker.lat = Lat;
            _marker.lng = Lon;
            //toolStripButton_Save.Image = Properties.Resources.SaveNotif_16x16;
            modified();
        }
        public bool ShowMarker()
        {
            return _showRepere;
        }

        #endregion

        #region SAVE CANCEL

        private void toolStripButton_SaveMarker_Click(object sender, EventArgs e)
        {
            //if (_marker.categories.Count > 0)
            {
                //string path = Path.Combine(Param.localPath_Small, Path.GetFileName(_marker.Img_Small));
                if (null != pictureBox_Small.Image)
                {
                    if (null != onSaveClick)
                        onSaveClick();
                    Init();
                }
                else
                {
                    MessageBox.Show(this, Param.RM.GetString("MB_SmallMissing"), Param.RM.GetString("MB_ErrorCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            /*else
            {
                MessageBox.Show(this, Param.RM.GetString("MB_CatMissing"), Param.RM.GetString("MB_ErrorCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }*/
        }

        private void toolStripButton_CancelMarker_Click(object sender, EventArgs e)
        {
            if (null != onCancelClick)
                onCancelClick();
        }

        #endregion

        private void modified()
        {
            toolStripButton_SaveMarker.Image = Properties.Resources.SaveNotif_16x16;
            if (null != onModifiedClick)
                onModifiedClick();
        }

        private void ToolStripButton_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void ToolStripButton_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
        }

        private void cueTextBox_Title_TextChanged(object sender, EventArgs e)
        {
            if (!_init)
            {
                if (string.Empty != cueTextBox_Title.Text)
                    _marker.title = cueTextBox_Title.Text;
                else _marker.title = _defaultTitle;
            }
            if (!_init)
                modified();
        }
    }
}
